<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
          >批量删除</el-button
        >
        <!-- <el-select v-model="query.address" placeholder="地址" class="handle-select mr10">
                    <el-option key="1" label="广东省" value="广东省"></el-option>
                    <el-option key="2" label="湖南省" value="湖南省"></el-option>
                </el-select> -->
        <el-input
          v-model="query.username"
          placeholder="用户名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="user_id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户账号"
          width="160"
        ></el-table-column>
        <el-table-column prop="ur_id" label="用户角色" width="160">
          <template slot-scope="scope">
            {{ getRoleNameById(scope.row.ur_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="uc_id" label="账户类型" width="160">
          <template slot-scope="scope">
            {{ getUserTypeNameById(scope.row.ur_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="user_state" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.user_state == 3">{{
              getUserState(scope.row.user_state)
            }}</el-tag>
            <el-tag type="success" v-else-if="scope.row.user_state == 1">{{
              getUserState(scope.row.user_state)
            }}</el-tag>
            <el-tag v-else>{{ getUserState(scope.row.user_state) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reg_time"
          width="200"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          prop="login_time"
          label="登录时间"
          width="200"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.currentPage"
          :page-size="query.pageSize"
          :page-count="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog
      title="编辑"
      :visible.sync="editVisible"
      width="30%"
      :append-to-body="true"
    >
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="用户账号">
          <label>{{ form.username }}</label>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="form.ur_id" placeholder="选择角色">
            <el-option
              v-for="(item, index) in userRoleList"
              :key="index"
              :label="item.role_name"
              :value="item.ur_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户类型">
          <el-select v-model="form.uc_id" placeholder="选择角色">
            <el-option
              v-for="(item, index) in userClassList"
              :key="index"
              :label="item.uc_name"
              :value="item.uc_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <label v-if="form.user_state != 3"
            ><el-tag>{{ getUserState(form.user_state) }}</el-tag></label
          >
          <label v-else
            ><el-tag type="danger">{{
              getUserState(form.user_state)
            }}</el-tag></label
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUserPagerData,
  getUserRoleList,
  getUserClassList,
  updateUserRoleByUserId,
} from "@/api";

export default {
  name: "ClientTable",
  data() {
    return {
      query: {
        username: "",
        currentPage: 1,
        pageSize: 10,
      },
      tableData: [],
      multipleSelection: [], //多选框数组
      delList: [], //批量删除
      editVisible: false, //默认编辑框不可见
      addVisible: false,
      vilidateBarcodeMessage: "",

      pageTotal: 0,
      form: {
        user_password: "123456",
      },
      idx: -1, //当前分页页面的第几行数据
      id: -1, //
      resetPassword: "",
      userRoleList: [],
      userClassList: [],
    };
  },
  components: {
    //引入外部组件，这里是定义
  },
  mounted() {
    this.InitData();
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    InitData() {
      this.getData();
      this.getUserRole();
      this.getUserClassList();
    },
    async getData() {
      let res = await getAllUserPagerData(this.query);

      if (res.code == 200) {
        this.tableData = res.data.data;
        this.pageTotal = res.data.pageTotal || 1;
      }
    },
    //加载用户角色列表信息
    async getUserRole() {
      let res = await getUserRoleList();
      if (res.code == 200) {
        //装载数据
        this.userRoleList = res.data;
      }
    },
    //显示角色方法
    getRoleNameById(urId) {
      const role = this.userRoleList.find((role) => role.ur_id === urId);
      return role ? role.role_name : "未知角色";
    },
    //加载企业分类信息
    async getUserClassList() {
      let res = await getUserClassList();
      if (res.code == 200) {
        this.userClassList = res.data;
      }
    },
    //显示企业类型方法
    getUserTypeNameById(ucId) {
      const userType = this.userClassList.find((type) => type.uc_id === ucId);
      return userType ? userType.uc_name : "未知类型";
    },
    //选择状态
    getUserState(num) {
      switch (num) {
        case 0:
          return "未开户";
          break;
        case 1:
          return "已开户";
          break;
        case 2:
          return "申请中";
          break;
        case 3:
          return "驳回";
          break;
        case 6:
          return "禁用";
          break;
        default:
          return "默认未开户";
      }
    },
    // 触发搜索按钮
    handleSearch() {
      //this.$set(this.query, 'pageIndex', 1);
      this.InitData();
    },
    // 删除操作
    handleDelete(index, row) {
      let ids = row.user_id;
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.saveDelete(ids);
          this.tableData.splice(index, 1);
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除方法封装
    async saveDelete(ids) {
      //删除多个
      // let res = await this.$http.post("deleteUser", { ids: ids });
      // if (res.data) {
      //   this.$message.success(`删除了${ids}`);
      //   this.InitData();
      // } else {
      //   this.$message.error(`删除了${ids}`);
      // }
    },
    // 批量删除
    delAllSelection() {
      const length = this.multipleSelection.length;
      let ids = "";
      //this.delList = this.delList.concat(this.multipleSelection);
      for (let i = 0; i < length; i++) {
        ids += this.multipleSelection[i].user_id + ",";
      }
      ids = ids.substring(0, ids.length - 1);

      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          //执行删除
          this.saveDelete(ids);
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      this.form = {};
      this.idx = index;
      this.form = row;
      this.editVisible = true;
    },
    cancelAdd() {
      this.editVisible = false;
      this.destroyed();
    },
    // 保存编辑
    async saveEdit() {
      this.editVisible = false;
      console.log(this.form);
      let res = await updateUserRoleByUserId(this.form);
      if (res.code == 200) {
        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
        this.InitData();
      } else {
        this.$message.error(`修改第 ${this.idx + 1} 行失败`);
      }

      // console.log(this.form);
      //this.$set(this.tableData, this.idx, this.form);
    },
    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      // this.$set(this.query, 'currentPage', val);
      this.query.currentPage = val;
      this.getData();
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.mg-left {
  margin-left: 10px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
